import { changeState } from './changeState';

let state = changeState('');

const createStore = () => {

    // getState获取状态
    const getState = () => state;


    // 观察者模式
    const listeners = [];
    // subscribe 订阅
    const subscribe = (listener) => listeners.push(listener);


    const dispatch = (action) => {
        state = changeState(action, state);
        // console.log(changeState(action), state);

        // publish 发布
        listeners.forEach((listener) => listener());
    };


    return {
        subscribe, // 订阅
        dispatch, // 发布
        getState, // 获取状态
    };
};

const store = createStore();

// 操作dom
const render = () => {
    document.querySelector('#count').innerHTML = store.getState().count;
};

store.subscribe(render);

export default store;
